
#include<QDebug>
#include "cameraThread.h"
#include<opencv2\imgproc\imgproc.hpp>
#include<sstream>
#include<opencv2\core\core.hpp>
#include<iostream>
#include<QDebug>
#include<qmutex.h>
int cameraThread::count=0; 

cameraThread::cameraThread(void)
{
	
	isStop=false;
	isFrameReady=false;
	qDebug()<<"cameraThread Constructor: " <<this->thread()->currentThread()<<this->thread()->currentThreadId();
}


cameraThread::~cameraThread(void)
{
		writer.release();
		capture.release();
}

void cameraThread::run()
{
	setPriority(QThread::TimeCriticalPriority);
	while(1)
	{
		if(isFrameReady)
		{
			double t=cv::getTickCount();
			//#pragma omp parallel section
			{
			//mutex.lock();
			cv::Mat output;
			//qDebug()<<"timestamp:"<<capture.get(CV_CAP_PROP_FORMAT);
			capture>>frame;
			cv::resize(frame,output,size);	
			writer<<output;
			}
			t = ((double)cv::getTickCount() - 
				t
				)*1000/cv::getTickFrequency();
			qDebug()<<"Frame time :"<<t;
			emit sendFrame(&frame);
			qDebug()<<"cameraThread::run() frame : " <<thread()->currentThread()<< thread()->currentThreadId();
			//mutex.unlock();
			//exec();
			//msleep(50);//reduce threads scheduling
			
		}
	}
}

void cameraThread::startCam(camCapture* show,
	QTimer *timer,
	int camera,
	const cv::string& filename,
	double fps, 
	cv::Size frameSize,
	bool isColor, 
	int fourcc )
{
	count++;// the number of cameras 
	size=frameSize;
	capture=cv::VideoCapture(camera);
	

	std::stringstream name;
	name<<filename<<count<<".avi";
	writer=cv::VideoWriter(name.str(), fourcc, fps, frameSize, isColor);

	if(capture.isOpened()&&writer.isOpened())
	{
		QObject::connect((QObject*)this,SIGNAL(sendFrame( cv::Mat*)),(QObject*)show,SLOT(receiveFrame(cv::Mat*)));//connect receive and send
		QObject::connect((QObject*)timer,SIGNAL(timeout()),(QObject*)this,SLOT(nextFrame()));
		start();//run this thread to get frames frome camera and display
	}
		qDebug()<<"Start thread " << thread()->currentThread()<< thread()->currentThreadId();
}

void cameraThread::stop()
{
	isStop=true;
}
void cameraThread::nextFrame()
{
	//cv::Mat output;
	//double t=cv::getTickCount();
	////qDebug()<<"timestamp:"<<capture.get(CV_CAP_PROP_FORMAT);
	//capture>>frame;
	//cv::resize(frame,output,size);	
	//writer<<output;
	//
	//t = ((double)cv::getTickCount() - t)*1000/cv::getTickFrequency();
	//qDebug()<<"hello from worker thread " << thread()->currentThreadId();
	//qDebug()<<"Frame time :"<<t;
	//emit sendFrame(&frame);
	
	isFrameReady=true;
}
